package com.soft.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.soft.entity.SensitiveWord;
import com.soft.service.SensitiveWordService;

/**
 * 敏感词接口（/sensitive-word）：
 * - 词库 CRUD：/add /delete/{id} /update /detail/{id} /list /list/active
 * - 内容检测：/filter 返回替换结果；/check 返回是否包含和命中词列表
 * - 维护：/refresh-cache 刷新缓存
 */
@RestController
@RequestMapping("/sensitive-word")
public class SensitiveWordController {
    
    @Autowired
    private SensitiveWordService sensitiveWordService;
    
    /**
     * 添加敏感词
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addSensitiveWord(@RequestBody SensitiveWord sensitiveWord) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1) 设置默认创建人（演示期从固定ID；真实环境应取自登录态）
            if (sensitiveWord.getCreatorId() == null) {
                sensitiveWord.setCreatorId(1);
            }
            // 2) 调用服务层新增
            boolean success = sensitiveWordService.addSensitiveWord(sensitiveWord);
            
            if (success) {
                // 3) 返回成功标识与提示
                response.put("success", true);
                response.put("message", "敏感词添加成功");
                return ResponseEntity.ok(response);
            } else {
                // 4) 失败时返回 400，便于前端提示
                response.put("success", false);
                response.put("message", "敏感词添加失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            // 5) 兜底异常处理
            response.put("success", false);
            response.put("message", "添加敏感词时发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除敏感词
     */
    @DeleteMapping("/delete/{wordId}")
    public ResponseEntity<Map<String, Object>> deleteSensitiveWord(@PathVariable Integer wordId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1) 调用服务层删除
            boolean success = sensitiveWordService.deleteSensitiveWord(wordId);
            
            if (success) {
                response.put("success", true);
                response.put("message", "敏感词删除成功");
                return ResponseEntity.ok(response);
            } else {
                // 2) 没删到记录也视为失败，返回400
                response.put("success", false);
                response.put("message", "敏感词删除失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除敏感词时发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 更新敏感词
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateSensitiveWord(@RequestBody SensitiveWord sensitiveWord) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1) 更新记录（通常要求包含 wordId）
            boolean success = sensitiveWordService.updateSensitiveWord(sensitiveWord);
            
            if (success) {
                response.put("success", true);
                response.put("message", "敏感词更新成功");
                return ResponseEntity.ok(response);
            } else {
                // 2) 更新失败返回400
                response.put("success", false);
                response.put("message", "敏感词更新失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新敏感词时发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取敏感词详情
     */
    @GetMapping("/detail/{wordId}")
    public ResponseEntity<SensitiveWord> getSensitiveWordDetail(@PathVariable Integer wordId) {
    // 1) 读取单条记录，若不存在返回404
        SensitiveWord sensitiveWord = sensitiveWordService.getSensitiveWordById(wordId);
        
        if (sensitiveWord != null) {
            return ResponseEntity.ok(sensitiveWord);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取所有敏感词列表
     */
    @GetMapping("/list")
    public ResponseEntity<List<SensitiveWord>> listAllSensitiveWords() {
    // 返回全量词库
        List<SensitiveWord> words = sensitiveWordService.listAllSensitiveWords();
        return ResponseEntity.ok(words);
    }
    
    /**
     * 获取激活状态的敏感词列表
     */
    @GetMapping("/list/active")
    public ResponseEntity<List<SensitiveWord>> listActiveSensitiveWords() {
    // 仅返回处于启用状态的词库
        List<SensitiveWord> words = sensitiveWordService.listActiveSensitiveWords();
        return ResponseEntity.ok(words);
    }
    

    
    /**
     * 过滤内容中的敏感词
     */
    @PostMapping("/filter")
    public ResponseEntity<Map<String, Object>> filterContent(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1) 解析待过滤内容
            String content = request.get("content");
            if (content == null) {
                response.put("success", false);
                response.put("message", "内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 2) 执行过滤并返回命中列表
            String filteredContent = sensitiveWordService.filterSensitiveContent(content);
            List<String> foundWords = sensitiveWordService.findSensitiveWords(content);
            
            response.put("success", true);
            response.put("originalContent", content);
            response.put("filteredContent", filteredContent);
            response.put("containsSensitive", !foundWords.isEmpty());
            response.put("sensitiveWords", foundWords);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "过滤内容时发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 检查内容是否包含敏感词
     */
    @PostMapping("/check")
    public ResponseEntity<Map<String, Object>> checkContent(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1) 解析内容并做存在性校验
            String content = request.get("content");
            if (content == null) {
                response.put("success", false);
                response.put("message", "内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 2) 检查是否包含敏感词及命中词清单
            boolean containsSensitive = sensitiveWordService.containsSensitiveWords(content);
            List<String> foundWords = sensitiveWordService.findSensitiveWords(content);
            
            response.put("success", true);
            response.put("containsSensitive", containsSensitive);
            response.put("sensitiveWords", foundWords);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查内容时发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 刷新敏感词缓存
     */
    @PostMapping("/refresh-cache")
    public ResponseEntity<Map<String, Object>> refreshCache() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 主动刷新内存/本地缓存，保证新词立即生效
            sensitiveWordService.refreshSensitiveWordsCache();
            response.put("success", true);
            response.put("message", "敏感词缓存刷新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "刷新缓存时发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}